// ignore_for_file: prefer_const_constructors, prefer_const_literals_to_create_immutables, sort_child_properties_last
import 'dart:async';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:junyeyishu/mianTab.dart';
import 'package:junyeyishu/ui/login/QGVerifyAliPage.dart';
// import '../../route.dart';
import "package:junyeyishu/utils/utils.dart";
import 'package:junyeyishu/widgets/QGCircleCheckWidget.dart';


class QGCodeLoginPage extends StatefulWidget {

 final String? invitation_code;
  const QGCodeLoginPage({this.invitation_code,super.key});
  @override
  State<QGCodeLoginPage> createState() => _QGCodeLoginPageState();
}

class _QGCodeLoginPageState extends State<QGCodeLoginPage> {


  bool check = true;
  final phoneController = TextEditingController();
  final codeController = TextEditingController();
  final QRcodeController = TextEditingController();

  String? sign;

  Timer? timer;
  int countdown = 0;

  @override
  void dispose() {
    timer?.cancel();
    phoneController.dispose();
    codeController.dispose();
    QRcodeController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {

    final uri = Uri.base; // 获取当前页面的 Uri 对象
  final code = uri.queryParameters['code']; // 获取 code 参数

     QRcodeController.text=code??'';

    return Column(
      children: [
        buildText("手机号验证码登录", 26.rpx, FontWeight.bold, 0xFF111111),
        SizedBox(height: 3.rpx),
        buildText("未注册的手机号验证后将自动创建新账户", 14.rpx, FontWeight.normal, 0xFF111111),
        SizedBox(height: 15.rpx),

        Container(
          margin: EdgeInsets.symmetric(horizontal: 20.rpx),
          padding: EdgeInsets.symmetric(horizontal: 20,vertical: 20),
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(20),
            color: Color(0XB3FFFFFF)
          ),
          child: Column(
            children: [
       
        buildPhone(),
        SizedBox(height: 10.rpx),
        buildCode(),
        SizedBox(height: 15.rpx),
        QRCode(),
        SizedBox(height: 40.rpx),
        buildButton(),
            ],
          ),
        )
       ,

        SizedBox(height: 15.rpx),
        buildAgreement(),
      ],
    );
  }

  buildText(text, fontSize, fontWeight, color) {
    return Container(
      alignment: Alignment.centerLeft,
      margin: EdgeInsets.only(left: 25.rpx),
      child: Text(
        text,
        style: TextStyle(
            fontSize: fontSize, fontWeight: fontWeight, color: Color(color)),
      ),
    );
  }

  buildPhone() {
    return 
    Container(
      height: 54.rpx,
            decoration: BoxDecoration(
              border: Border(
                bottom: BorderSide(
                  color: Color(0XFFA6D9D4)
                )
              ),
            ),
      child: Row(
      children: [
        Text('+86',style: TextStyle(fontSize: 16,color: Color(0XFF111111))),
        Container(
          padding: EdgeInsets.only(right: 15.rpx),
          height: 15.rpx,
          decoration: BoxDecoration(
            border: Border(
              right: BorderSide(
                color: Color(0XFF999999)
              )
            )
          ),
        ),
        Expanded(
            child: Container(
          height: 54.rpx,
          decoration: BoxDecoration(
             
           borderRadius: BorderRadius.circular(10.rpx)),
          child: Padding(
            padding: EdgeInsets.only(left: 25.rpx, right: 20.rpx),
            child: Row(
              children: [
                Expanded(
                  child: TextField(
                      controller: phoneController,
                      keyboardType: TextInputType.number,
                      textInputAction: TextInputAction.done,
                      cursorColor: Color(0xFF111111),
                      style: TextStyle(
                          color: Color(0xFF111111),
                          fontSize: 13.rpx,
                          fontWeight: FontWeight.bold),
                      decoration: InputDecoration(
                        hintText: "请输入手机号",
                        hintStyle: TextStyle(
                            color: Color(0xFF739D98),
                            fontWeight: FontWeight.normal),
                        enabledBorder: InputBorder.none,
                        focusedBorder: InputBorder.none,
                      )),
                ),
              ],
            ),
          ),
        )),
      ],
    ),
    )
    ;
  }

  buildCode() {
    return Row(
      children: [
        Expanded(
          child: Container(
            height: 54.rpx,
            decoration: BoxDecoration(
              border: Border(
                bottom: BorderSide(
                  color: Color(0XFFA6D9D4)
                )
              ),
            ),

            child: Padding(
              padding: EdgeInsets.only(left: 5.rpx, right: 0.rpx),
              child: Row(
                children: [
                  Expanded(
                    child: TextField(
                        controller: codeController,
                        keyboardType: TextInputType.number,
                        textInputAction: TextInputAction.done,
                        cursorColor: Color(0xFF111111),
                        style: TextStyle(
                            color: Color(0xFF111111),
                            fontSize: 13.rpx,
                            fontWeight: FontWeight.bold),
                        decoration: InputDecoration(
                          hintText: "请输入验证码",
                          hintStyle: TextStyle(
                              color: Color(0xFF999999),
                              fontWeight: FontWeight.normal), //修改颜色
                          enabledBorder: InputBorder.none,
                          focusedBorder: InputBorder.none,
                        )),
                  ),
                  TextButton(
                    onPressed: () {
                      toVerify();
                    },
                    child: Text(
                      countdown > 0 ? "$countdown秒重新发送" : "发送验证码",
                      style: TextStyle(
                          color: Color(0xFF111111),
                          fontSize: 14.rpx,
                          fontWeight: FontWeight.bold),
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
      ],
    );
  }

  QRCode() {
    return Row(
      children: [
        Expanded(
          child: Container(
            height: 54.rpx,
            decoration: BoxDecoration(
              border: Border(
                bottom: BorderSide(
                  color: Color(0XFFA6D9D4)
                )
              ),
            ),

            child: Padding(
              padding: EdgeInsets.only(left: 5.rpx, right: 0.rpx),
              child: Row(
                children: [
                  Expanded(
                    child: TextField(
                        controller: QRcodeController,
                        textInputAction: TextInputAction.done,
                        cursorColor: Color(0xFF111111),
                        style: TextStyle(
                            color: Color(0xFF111111),
                            fontSize: 13.rpx,
                            fontWeight: FontWeight.bold),
                        decoration: InputDecoration(
                          hintText: "请输入邀请码（选填）",
                          hintStyle: TextStyle(
                              color: Color(0xFF999999),
                              fontWeight: FontWeight.normal), //修改颜色
                          enabledBorder: InputBorder.none,
                          focusedBorder: InputBorder.none,
                        )),
                  ),
                ],
              ),
            ),
          ),
        ),
      ],
    );
  }

  buildButton() {
    return Row(
      children: [
        Expanded(
          child: Container(
            height: 50.rpx,
            decoration: BoxDecoration(
              gradient: const LinearGradient(
                begin: Alignment.centerLeft,
                end: Alignment.centerRight,
                colors: [Color(0xFF4AE3FF), Color(0xFF44FFF0)],
              ),
              borderRadius: BorderRadius.circular(25.rpx),
            ),
            child: TextButton(
              onPressed: () {
                onLogin();
              },
              child: Text(
                '登录',
                style: TextStyle(
                    color: Color(0xFF111111),
                    fontSize: 16.rpx,
                    fontWeight: FontWeight.bold),
              ),
            ),
          ),
        ),
      ],
    );
  }

  buildAgreement() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        QGCircleCheckWidget(
            size: 12.rpx,
            select: check,
            padding: EdgeInsets.symmetric(vertical: 5.rpx, horizontal: 5.rpx),
            image: "login_checks",
            onTap: (select) {
              check = select;
              setState(() {});
            }),
        SizedBox(width: 3.rpx),
        Text(
          '已阅读并同意',
          style: TextStyle(
              color: Color(0xFF666666),
              fontSize: 12.rpx,
              fontWeight: FontWeight.normal),
        ),
        GestureDetector(
          onTap: onAgreement,
          child: Container(
            color: Colors.transparent,
            padding: EdgeInsets.symmetric(vertical: 10.rpx),
            child: Text(
              "《服务协议》",
              style: TextStyle(
                fontSize: 12.rpx,
                color: Color(0xFF5E85E3),
              ),
            ),
          ),
        ),
        GestureDetector(
          onTap: onPrivacy,
          child: Container(
            color: Colors.transparent,
            padding: EdgeInsets.symmetric(vertical: 10.rpx),
            child: Text(
              "《隐私政策》",
              style: TextStyle(
                fontSize: 12.rpx,
                color: Color(0xFF5E85E3),
              ),
            ),
          ),
        ),
      ],
    );
  }

  start() {
    countdown = 60;
    setState(() {});
    timer = Timer.periodic(Duration(seconds: 1), (timer) {
      countdown--;
      if (countdown == 0) {
        timer.cancel();
      }
      if (mounted) {
        setState(() {});
      }
    });
  }

  toVerify() {
    if (countdown > 0) {
      return;
    }

    unfocus(context);

    if (!check) {
      toast("请阅读并同意协议");
      return;
    }

    var phone = phoneController.text;
    if (phone.isEmpty || phone.length != 11) {
      toast("请输入正确手机号");
      return;
    }
    print('4444');

    showDialog(
        context: context,
        builder: (context) {
          return QGVerifyAliPage(phone: phone);
        }).then((value) {

        if (value is! Map) return;
        sign = value["sign"];
        start();
      });

  }

  onLogin() async {
    unfocus(context);

    if (!check) {
      toast("请阅读并同意协议");
      return;
    }

    var phone = phoneController.text;
    var code = codeController.text;

    if (phone.isEmpty || phone.length != 11) {
      toast("请输入正确手机号");
      return;
    }
    if (code.isEmpty) {
      toast("请输入验证码");
      return;
    }

    final param = {};
    param["phone"] = phone;
    param["code"] = code;
    param["sign"] = sign;

    final aa = FormData.fromMap({"phone":phone,"code":code,"sign":'sign',"invitation_code":QRcodeController.text});

    Network.post(url_login, data: aa, context: context).then((res) async {
      if (!res.success) {
        toast(res.msg);
        return;
      }

      res.data["phone"] = phone;
      await User.login(res.data);
      toast(res.msg);

      eventBus.fire(EventLogin());


      Navigator.of(context).pushAndRemoveUntil(
        MaterialPageRoute(builder: (context) => MainTab()), 
        (route) => false // 清除所有历史路由
      );

      // Future.delayed(Duration(seconds: 1), () {
      //   Navigator.of(context).pop()
      // });

    });
  }

  onAgreement() {
    var args = {
      "title": "用户协议",
      "content": getUserAgreement(),
    };
    Navigator.of(context).pushNamed(PageRule, arguments: args);
  }

  onPrivacy() {
    var args = {
      "title": "隐私政策",
      "content": getPrivacyPolicy(),
    };
    Navigator.of(context).pushNamed(PageRule, arguments: args);
  }
}
